package com.example.demo.utils.similarity;

import com.example.demo.po.bug.Bug;
import com.example.demo.vo.bug.BugInfoVO;

import java.util.List;

/**
 * 基于公共子串的相似度算法
 */
public class StrSimilarity {
    public static double reportSimilarity(List<BugInfoVO> report1,List<Bug> report2){
        StringBuilder b1=new StringBuilder();
        StringBuilder b2=new StringBuilder();
        for(BugInfoVO bug:report1){
            b1.append(bug.getDescription()).append(bug.getProcedure());
        }
        for(Bug bug:report2){
            b2.append(bug.getDescription()).append(bug.getProcedure());
        }
        return getSimilarity(b1.toString(),b2.toString());

    }

    private static double getSimilarity(String strA, String strB){
        String newStrA = removeSign(strA);
        String newStrB = removeSign(strB);
        if(newStrA.length()<newStrB.length()){
            String temp=newStrA;
            newStrA=newStrB;
            newStrB=temp;
        }
        int temp = newStrA.length();
        int temp2 = longestCommonSubstring(newStrA, newStrB).length();
        return temp2 * 1.0 / temp;
    }
    //排除标点符号影响
    private static String removeSign(String str) {
        StringBuilder sb = new StringBuilder();
        for (char item : str.toCharArray())
            if (charReg(item)){
                sb.append(item);
            }
        return sb.toString();
    }

    private static boolean charReg(char charValue) {
        return (charValue >= 0x4E00 && charValue <= 0X9FA5) || (charValue >= 'a' && charValue <= 'z')
                || (charValue >= 'A' && charValue <= 'Z')  || (charValue >= '0' && charValue <= '9');
    }

    private static String longestCommonSubstring(String strA, String strB) {
        char[] chars_strA = strA.toCharArray();
        char[] chars_strB = strB.toCharArray();
        int m = chars_strA.length;
        int n = chars_strB.length;
        int[][] matrix = new int[m + 1][n + 1];
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (chars_strA[i - 1] == chars_strB[j - 1])
                    matrix[i][j] = matrix[i - 1][j - 1] + 1;
                else
                    matrix[i][j] = Math.max(matrix[i][j - 1], matrix[i - 1][j]);
            }
        }
        char[] result = new char[matrix[m][n]];
        int currentIndex = result.length - 1;
        while (matrix[m][n] != 0) {
            if (matrix[n] == matrix[n - 1])
                n--;
            else if (matrix[m][n] == matrix[m - 1][n])
                m--;
            else {
                result[currentIndex] = chars_strA[m - 1];
                currentIndex--;
                n--;
                m--;
            }
        }
        return new String(result);
    }

}
